package com.beiye.drivertransport.SubActivity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.UpPhotoBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.utils.FileUtil;
import com.beiye.drivertransport.utils.ImageUtil;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.view.ChangeView;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//课程详情里个人头像上传
public class TakePersonPictureActivity extends AppCompatActivity {
    private int screenWidth;
    private int screenHeight;
    private File tempFile;
    //    //请求访问外部存储
//    private static final int READ_EXTERNAL_STORAGE_REQUEST_CODE = 103;
    //请求写入外部存储
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 104;
    private int type;
    //请求相机
    private static final int REQUEST_CAPTURE = 100;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_person_picture);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);// 取得窗口属性
        // 窗口的宽度
        screenWidth = dm.widthPixels;
        // 窗口高度
        screenHeight = dm.heightPixels;
        ViewGroup viewGroup=(ViewGroup)this.findViewById(android.R.id.content);
        ChangeView.changeViewSize(viewGroup, screenWidth, screenHeight);

        //权限判断
        if (ContextCompat.checkSelfPermission(TakePersonPictureActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(TakePersonPictureActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
        } else {
            gotoCamera();
        }

    }

    /**
     * 跳转到照相机
     */
    private void gotoCamera() {
        Log.d("evan", "*****************打开相机********************");
        //创建拍照存储的图片文件
        tempFile = new File(FileUtil.checkDirPath(Environment.getExternalStorageDirectory().getPath() + "/image/"), System.currentTimeMillis() + ".jpg");

        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //设置7.0中共享文件，分享路径定义在xml/file_paths.xml
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(TakePersonPictureActivity.this, com.beiye.drivertransport.BuildConfig.APPLICATION_ID + ".fileProvider", tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        }
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case REQUEST_CAPTURE: //调用系统相机返回
                if (resultCode == Activity.RESULT_OK) {
                    Uri uri = Uri.fromFile(tempFile);
                    if (uri == null) {
                        return;
                    }
                    String cropImagePath = FileUtil.getRealFilePathFromUri(TakePersonPictureActivity.this, uri);
                    File file = new File(cropImagePath);
                       try {
                        FileInputStream fis = new FileInputStream(file);
                        Bitmap bitmapByUrl = BitmapFactory.decodeStream(fis);
                        bitmapByUrl = compressScale(bitmapByUrl);
//                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss ");
//                        Date curDate = new Date(System.currentTimeMillis());//获取当前系统时间
//                        String str = formatter.format(curDate);

                        Bitmap bitmap = ImageUtil.drawTextToRightBottom(TakePersonPictureActivity.this, bitmapByUrl, "", ChangeView.adjustFontSize(screenWidth, screenHeight), getResources().getColor(R.color.organger), 5, 5);
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        bos.flush();
                        bos.close();
                        LoginUserBean userInfo = UserManger.getUserInfo();
                        LoginUserBean.DataBean databean = userInfo.getData();
                         String userId = databean.getUserId();
                         uploadImg(file, userId);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {

                    }





//                    try {
//                        FileInputStream fis = new FileInputStream(file);
//                        Bitmap bitmapByUrl = BitmapFactory.decodeStream(fis);
//                        bitmapByUrl = compressScale(bitmapByUrl);
////                            bitmapByUrl = rotaingImageView(90, bitmapByUrl);
//                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss ");
//                        Date curDate = new Date(System.currentTimeMillis());//获取当前系统时间
//                        String str = formatter.format(curDate);
//
//                        Bitmap bitmap = ImageUtil.drawTextToRightBottom(TakePhotoVehTeeActivity.this, bitmapByUrl, str, ChangeView.adjustFontSize(screenWidth, screenHeight), getResources().getColor(R.color.organger), 5, 5);
//                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
//                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
//                        bos.flush();
//                        bos.close();
//                        returnResult(file);
//                    } catch (FileNotFoundException e) {
//                        e.printStackTrace();
//                    } catch (IOException e) {
//
//                    }

                } else if (resultCode == Activity.RESULT_CANCELED) {
                    setResult(2, null);
                    finish();
                }
                break;


        }
    }

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private final OkHttpClient client = new OkHttpClient();

    private void uploadImg(File mediaFile, String userId) {
        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        if (mediaFile != null) {
            builder.addFormDataPart("headPhoto", mediaFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, mediaFile));
            builder.addFormDataPart("userId", userId);
        }
        mProgressDialog = new ProgressDialog(TakePersonPictureActivity.this, ProgressDialog.THEME_HOLO_DARK);
        mProgressDialog.setMessage("上传中...");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url(AppInterfaceConfig.BASE_URL + "wx/uploadOfHeadPhoto")//地址
                .post(requestBody)//添加请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtils.e("上传失败", e.getLocalizedMessage());
                mProgressDialog.dismiss();
                // 设置回传码和Intent
                setResult(2, null);
                finish();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mProgressDialog.dismiss();
                String str = response.body().string();
                LogUtils.e("上传成功", str);
                UpPhotoBean upPhotoBean = JSON.parseObject(str, UpPhotoBean.class);
                final String photoUrl = upPhotoBean.getData();
                boolean result = upPhotoBean.isResult();
                if (result) {
                    Intent intent = new Intent();
                    // 设置要回传的数据
                    intent.putExtra("url", photoUrl);
                    // 设置回传码和Intent
                    setResult(1, intent);
                    finish();
                } else {
                    LogUtils.e("上传空值", photoUrl);
                    setResult(2, null);
                    finish();
                }

//                LogUtils.e("上传图片", photoUrl);
//                LoginUserBean userInfo = UserManger.getUserInfo();
//                String userId = userInfo.getData().getUserId();
//                SharedPreferences sp = getSharedPreferences("durationandformat1" + userId,
//                        Context.MODE_PRIVATE);
//                SharedPreferences.Editor edit = sp.edit();
//                edit.putString("photoUrl",photoUrl);
//                edit.commit();
//                Looper.prepare();
//                AlertDialog.Builder builder = new AlertDialog.Builder(SpecifiedLearningCourseDetailsActivity.this);
//                View view = View
//                        .inflate(SpecifiedLearningCourseDetailsActivity.this, R.layout.diolog_learn_person_layout, null);
////                    TextView tv_message = (TextView) view
////                            .findViewById(R.id.message);//输入内容
////                    tv_message.setText("人脸识别失败,请面向镜头重新照相或者重新上传“我的”头像");
//                TextView btn_sure = (TextView) view.findViewById(R.id.positiveButton);
//                TextView btn_cancel = (TextView) view.findViewById(R.id.negativeButton);
//                TextView btn_message = (TextView) view.findViewById(R.id.message);
//                btn_message.setText("您已重新上传了个人头像，可点击“重新拍照”再次认证");
//                btn_cancel.setText("我的头像");
//                final AlertDialog dialog = builder.create();
//                dialog.show();
//                dialog.getWindow().setContentView(view);
//                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//                dialog.setCancelable(false);
//                btn_sure.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        dialog.dismiss();
//                        LoginUserBean userInfo = UserManger.getUserInfo();
//                        String userId = userInfo.getData().getUserId();
//                        SharedPreferences sp = getSharedPreferences("durationandformat1" + userId,
//                                Context.MODE_PRIVATE);
//                        int faceRecgMark = sp.getInt("faceRecgMark", 0);
//                       // String photoUrl = sp.getString("photoUrl", "");
//                        Bundle bundle = new Bundle();
//                        bundle.putInt("faceRecgMark", faceRecgMark);
//                        bundle.putString("photoUrl",photoUrl);
//                        startActivityForResult(TakefacePhotoActivity.class,bundle, 0);
//
//                    }
//                });
//                btn_cancel.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        dialog.dismiss();
////                            timer1.cancel();
////                            timerTask=null;
////                            timer1=null;
////                            LoginUserBean userInfo = UserManger.getUserInfo();
////                            String userId = userInfo.getData().getUserId();
////                            SharedPreferences sp1 = getSharedPreferences("durationandformat1" + userId,
////                                    Context.MODE_PRIVATE);
////                            SharedPreferences.Editor edit = sp1.edit();
////                            int otcSn1 = sp1.getInt("otcSn", 0);
////                            int learnsn = sp1.getInt("learnsn", 0);
////                            edit.remove("imgurl" + otcSn1+learnsn);
////                            edit.remove("format" + otcSn1+learnsn);
////                            edit.remove("firsttime" + otcSn1);
////                            edit.remove("num" + otcSn1);
////                            edit.remove("accessAudioUrl"+otcSn1+learnsn);
////                            edit.remove("intfirsttime" + otcSn1);
////                            edit.remove("tag" + otcSn1);
////                            edit.commit();
////                            finish();
//                        showTakePhotoPopupWindow();
//                    }
//                });
//
//                Looper.loop();

            }
        });

    }


    /**
     * 外部存储权限申请返回
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                gotoCamera();
            }
        }
    }
    /**
     * 图片按比例大小压缩方法
     *
     * @param image （根据Bitmap图片压缩）
     * @return
     */
    public static Bitmap compressScale(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        // 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
        if (baos.toByteArray().length / 1024 > 1024) {
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //Log.i(TAG, w + "---------------" + h);
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        // float hh = 800f;// 这里设置高度为800f
        // float ww = 480f;// 这里设置宽度为480f
        float hh = 600f;
        float ww = 450f;
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) { // 如果高度高的话根据高度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be; // 设置缩放比例
        // newOpts.inPreferredConfig = Config.RGB_565;//降低图片从ARGB888到RGB565
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return bitmap;
        //return bitmap;
    }
}